<template>
  <el-form
    label-width="96px"
    label-position="left"
    size="mini"
    class="wf-collapse-form"
  >

    <el-collapse :value="printTemplates" v-if="printTemplates.length > 0">
      <el-collapse-item :key="code" v-for="code in printTemplates" :name="code">
        <template slot="title">
          {{ `${$t("模版")}-`
          }}<l-wordprint-label :value="code"></l-wordprint-label>【{{ code }}】
        </template>
        <div style="padding: 0 8px;">
          <el-form-item :label="$t('批量打印节点')" prop="id">
            <l-select
              v-model="formData[`${code}_node`]"
              :placeholder="$t('请选择节点')"
              valueKey="id"
              labelKey="name"
              :options="nodeOptions(code)"
            ></l-select>
          </el-form-item>
        </div>
        <div style="height: 40px;">
          <div style="padding-left:8px;float:left;">
            <el-button-group>
              <el-button
                size="mini"
                icon="el-icon-plus"
                @click="handlePostClick(code)"
                >{{ $t("岗位") }}</el-button
              >
              <el-button
                size="mini"
                icon="el-icon-plus"
                @click="handleRoleClick(code)"
                >{{ $t("角色") }}</el-button
              >
              <el-button
                size="mini"
                icon="el-icon-plus"
                @click="handleUserClick(code)"
                >{{ $t("用户") }}</el-button
              >
            </el-button-group>
          </div>
          <div style="padding-right:8px;float:right;">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleClearClick(code)"
              >{{ $t("清空") }}</el-button
            >
          </div>
        </div>
        <l-table
          height="notset"
          :columns="columns"
          :dataSource="tableData[code] || []"
        >
          <template v-slot:type="scope">
            {{ typeFormat(scope.row.type) }}
          </template>
          <l-table-btns
            :isAuth="false"
            :btns="tableBtns"
            @click="handleTableBtnClick($event, code)"
          ></l-table-btns>
        </l-table>
      </el-collapse-item>
    </el-collapse>
    <div v-else style="padding:16px;">
        <el-alert
            :title="$t('权限说明')"
            type="info"
            :description="$t('在节点设置中，选择打印模版')"
            show-icon
            :closable="false"
            >
        </el-alert>
    </div>

    <l-dialog
      :title="$t('添加岗位')"
      :visible.sync="selectPostVisible"
      :height="480"
      width="1024px"
      @ok="handlePostSelectOk"
      @closed="handlePostSelectClosed"
    >
      <l-post-select-panel ref="postSelectPanel"></l-post-select-panel>
    </l-dialog>

    <l-dialog
      :title="$t('添加角色')"
      :visible.sync="selectRoleVisible"
      :height="480"
      width="800px"
      @ok="handleRoleSelectOk"
      @closed="handleRoleSelectClosed"
    >
      <l-role-select-panel ref="roleSelectPanel"></l-role-select-panel>
    </l-dialog>

    <l-dialog
      :title="$t('添加用户')"
      :visible.sync="selectUserVisible"
      :height="480"
      width="1024px"
      @ok="handleUserSelectOk"
      @closed="handleUserSelectClosed"
    >
      <l-user-select-panel ref="userSelectPanel"></l-user-select-panel>
    </l-dialog>
  </el-form>
</template>

<script>
export default {
  name: "auth-print-config",
  props: {
    wfData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      formData: {},

      columns: [
        { label: "类型", prop: "type", width: "60", align: "center" },
        { label: "名称", prop: "name", minWidth: "100" },
      ],
      tableBtns: [{ prop: "Delete", label: "删除" }],
      tableData: {},

      selectPostVisible: false,
      selectRoleVisible: false,
      selectUserVisible: false,

      printCode: "",
    };
  },

  computed: {
    // 打印模版
    printTemplates() {
      let printCodes = [];
      for (let item of this.wfData) {
        if (
          item.formWrodPrintCode &&
          printCodes.indexOf(item.formWrodPrintCode) === -1
        ) {
          printCodes.push(item.formWrodPrintCode);
        }
      }
      return printCodes;
    }
  },
  created() {
    this.lr_loadDblink();
  },
  methods: {
    nodeOptions(code) {
      let res = []
      let startNode = this.wfData.find((t) => t.type === "startEvent");
      let list = this.wfData.filter((t) => t.name && t.type != "startEvent");
      for(let node of list){
        if((node.isInherit && startNode.formWrodPrintCode == code) || node.formWrodPrintCode == code){
          res.push(res);
        }
      }
      return list;
    },
    handlePostClick(code) {
      this.printCode = code;
      this.selectPostVisible = true;
    },
    handlePostSelectClosed() {
      this.$refs.postSelectPanel.resetForm();
    },
    async handlePostSelectOk() {
      let postList = await this.$refs.postSelectPanel.getForm();
      let selectData = postList.map((t) => {
        return { type: 1, id: t.f_PostId, name: t.name };
      });
      this.addTableData(selectData);
      this.selectPostVisible = false;
    },

    handleRoleClick(code) {
      this.printCode = code;
      this.selectRoleVisible = true;
    },
    handleRoleSelectClosed() {
      this.$refs.roleSelectPanel.resetForm();
    },
    async handleRoleSelectOk() {
      let select = await this.$refs.roleSelectPanel.getForm();
      let selectData = select.map((t) => {
        return { type: 2, id: t.f_RoleId, name: t.f_FullName };
      });
      this.addTableData(selectData);
      this.selectRoleVisible = false;
    },

    handleUserClick(code) {
      this.printCode = code;
      this.selectUserVisible = true;
    },
    handleUserSelectClosed() {
      this.$refs.userSelectPanel.resetForm();
    },
    async handleUserSelectOk() {
      let select = await this.$refs.userSelectPanel.getForm();
      let selectData = select.map((t) => {
        return { type: 3, id: t.f_UserId, name: t.name };
      });
      this.addTableData(selectData);
      this.selectUserVisible = false;
    },

    addTableData(selectData) {
      let tableData = this.tableData[this.printCode] || [];
      let addData = selectData.filter(
        (t) => tableData.findIndex((t2) => t2.id == t.id) == -1
      );
      this.$set(this.tableData, this.printCode, tableData.concat(addData));

      //this.tableData[this.printCode] = tableData.concat(addData);
    },
    handleTableBtnClick(btn, code) {
      this.tableData[code].splice(btn.rowIndex, 1);
    },
    handleClearClick() {
      this.tableData[this.printCode] = [];
    },
    typeFormat(type) {
      switch (type) {
        case 1:
          return this.$t("岗位");
        case 2:
          return this.$t("角色");
        case 3:
          return this.$t("用户");
      }
    },

    resetForm() {
      this.$refs.form && this.$refs.form.resetFields();
      this.formData = {};
      this.tableData = {};
    },

    // 校验表单
    validateForm() {
      let printTemplates = this.printTemplates;
      for (let code of printTemplates) {
        let tableData = this.tableData[code] || [];
        if (this.formData[`${code}_node`] && tableData.length == 0) {
          this.$message({
            type: "warning",
            message: this.$t("请设置批量打印权限,") + code + "!",
          });
          return false;
        } else if (!this.formData[`${code}_node`] && tableData.length > 0) {
          this.$message({
            type: "warning",
            message: this.$t("请设置批量打印节点,") + code + "!",
          });
          return false;
        }
      }
      return true;
    },
    setForm({authData}) {
      let res = {};
      for(let item of authData){
        let { type, id, name } = item;
        let names = name.split('|');
        let point = {
          type,
          id,
          name:names[0]
        };
        let list = res[names[1]] || [];
        list.push(point);
        res[names[1]] = list;
        this.$set(this.formData,`${names[1]}_node`,names[2])
      }
      //this.formData = data.f_AuthType;
      this.tableData = res;
    },
    getForm() {
      let authData = [];
      for (let code of this.printTemplates) {
        let tableData = this.tableData[code] || [];
        if (this.formData[`${code}_node`] && tableData.length > 0) {
          for (let item of tableData) {
            let { type, id, name } = item;
            let point = {
              type,
              id,
              name:`${name}|${code}|${this.formData[`${code}_node`]}`
            };
            authData.push(point);
          }
        }
      }
      return {
        authData,
      };
    },
  },
};
</script>
